package com.taotao.sso.service;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.ibatis.javassist.expr.NewArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.utils.CookieUtils;
import com.taotao.common.utils.JsonUtils;
import com.taotao.pojo.TbUser;
import com.taotao.sso.component.JedisClient;
import com.taotao.sso.pojo.CartItem;

@Service
public class CartItemServiceImpl implements CartItemService {
	@Autowired
	private LoginService loginService;
	@Autowired
	private JedisClient jedisClient;
	@Value("${REDIS_USER_CARTITEM}")
	private String REDIS_USER_CARTITEM;

	/**
	 * 根据用户登录的token获取用户id,查询redis中对应用户的购物车列表
	 */
	@Override
	public TaotaoResult getCartItemList(String token) {
		TaotaoResult taotaoResult = loginService.getUserByToken(token);
		if (taotaoResult.getData() != null) {
			TbUser user = (TbUser) taotaoResult.getData();
			long id = user.getId();
			String json = jedisClient.get(REDIS_USER_CARTITEM + ":" + id);
			if (json == null) {
				return TaotaoResult.ok(new ArrayList<CartItem>());
			}
			List<CartItem> cartItems = JsonUtils.jsonToList(json,
					CartItem.class);
			return TaotaoResult.ok(cartItems);
		}
		return TaotaoResult.ok(new ArrayList<CartItem>());
	}

	/**
	 * 接收用户购物车列表信息,设置在redis缓存中
	 */
	@Override
	public TaotaoResult setCartItemList(List<CartItem> cartItemList,
			HttpServletRequest request,String token) {
		TaotaoResult taotaoResult = loginService.getUserByToken(token);
		if (taotaoResult.getData() != null) {
			TbUser user = (TbUser) taotaoResult.getData();
			long id = user.getId();
			if (cartItemList.isEmpty()) {
				jedisClient.expire(REDIS_USER_CARTITEM + ":" + id, 0);
				return TaotaoResult.ok();
			}
			String cartItems = JsonUtils.objectToJson(cartItemList);
			jedisClient.set(REDIS_USER_CARTITEM + ":" + id, cartItems);
			return TaotaoResult.ok();
		}
		return TaotaoResult.ok();
	}

}
